//
//  ASDetailBottomView.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/30.
//

#import "ASDetailBottomView.h"
#import "BDFCustomPhotoAlbum.h"
#import "ASHomeApi.h"

static NSString *ASDetailBottomSubCellStr = @"ASDetailBottomSubCell";
@interface ASDetailBottomSubCell : UICollectionViewCell
@property (strong, nonatomic) UIImageView *iconImage;
@property (strong, nonatomic) UILabel *titleLab;
@end
@implementation ASDetailBottomSubCell
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.iconImage];
        [self.contentView addSubview:self.titleLab];
        [self setAllViewLayout];
    }
    return self;
}

- (void)setAllViewLayout{
    @weakify(self);
    [self.iconImage mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.top.mas_equalTo(9);
        make.centerX.mas_equalTo(self.contentView.mas_centerX);
    }];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.centerX.mas_equalTo(self.contentView.mas_centerX);
        make.top.mas_equalTo(self.iconImage.mas_bottom).mas_offset(8);
    }];
}
-(UIImageView *)iconImage{
    if (!_iconImage) {
        _iconImage = [UIImageView new];
    }
    return _iconImage;
}

- (UILabel *)titleLab{
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.font = [UIFont systemFontOfSize:13];
        _titleLab.textColor = [UIColor colorWithHexString:@"#333333"];
        _titleLab.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLab;
}

@end

@implementation ASDetailBottomView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.imageArr = [NSMutableArray arrayWithArray:@[@"details_sc",@"details_bc"]];
        self.titleArr = [NSMutableArray arrayWithArray:@[@"收藏",@"保存"]];
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(20);
            make.right.mas_equalTo(-20);
            make.bottom.mas_equalTo(-Height_SafeAreaBottom);
        }];
    }
    return self;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [UICollectionViewFlowLayout new];
        fl.minimumLineSpacing = 0;
        fl.minimumInteritemSpacing = 0;
        fl.itemSize = CGSizeMake((SCREEN_WIDTH-40) / self.imageArr.count, 56);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
        _collectionView.backgroundColor = self.backgroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[ASDetailBottomSubCell class] forCellWithReuseIdentifier:ASDetailBottomSubCellStr];
    }
    return _collectionView;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ASDetailBottomSubCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ASDetailBottomSubCellStr forIndexPath:indexPath];
    if (self.imageArr.count > indexPath.row) {
        [cell.iconImage setImage:[UIImage imageNamed:self.imageArr[indexPath.row]]];
    }
    if (self.titleArr.count > indexPath.row) {
        cell.titleLab.text = self.titleArr[indexPath.row];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
//        [self showShareView];
        [self clickCollection];

    }else if (indexPath.row == 1) {
//        [self clickCollection];
        [self downLoadData];
    }else if (indexPath.row == 2) {
        [self downLoadData];
    }
}

- (void)setType:(NSInteger)type{
    _type = type;
    [self loadCollectionData];
}

///加载收藏的数据
- (void)loadCollectionData{
    self.collectionArr = [NSMutableArray new];
    NSString * temp  = NSTemporaryDirectory();
    NSString * filePath;
    if (self.type == 1) {
        filePath = [temp stringByAppendingPathComponent:ExpressionCollection];
    }else{
        filePath = [temp stringByAppendingPathComponent:COLLECTIONKEY];
    }
    NSArray *collArr =  [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    [self.collectionArr addObjectsFromArray:collArr];
}

- (void)setModel:(ASHomeMainModel *)model{
    _model = model;
    NSInteger collIndex = 1;
    if (self.imageArr.count < 3) {
        collIndex = 0;
    }
    if (self.imageArr.count > collIndex && self.titleArr.count > collIndex && self.collectionArr.count > 0 && [model.tID isNotBlank]  && [model.thumb isNotBlank]) {
        [self.imageArr replaceObjectAtIndex:collIndex withObject:@"details_sc"];
        [self.titleArr replaceObjectAtIndex:collIndex withObject:@"收藏"];
        model.is_collect = @"0";

        for (ASHomeMainModel *subM in self.collectionArr) {
            if ([subM.tID isEqualToString:model.tID] && [subM.thumb isEqualToString:model.thumb]) {
                model.is_collect = @"1";
                [self.imageArr replaceObjectAtIndex:collIndex withObject:@"details_ysc"];
                [self.titleArr replaceObjectAtIndex:collIndex withObject:@"已收藏"];
                break;
            }
        }
        [self.collectionView reloadData];
    }
}

///点击收藏
- (void)clickCollection{
    [ASTool addUMTongJiKey:@"details" subKey:self.type>0?@"expression_detail":@"portrail_detail" titleStr:@"收藏"];
    if (self.model) {
        if (self.model.is_collect.integerValue > 0) {
            self.model.is_collect = @"0";
            [self.imageArr replaceObjectAtIndex:0 withObject:@"details_sc"];
            [self.titleArr replaceObjectAtIndex:0 withObject:@"收藏"];
            [MBProgressHUD showSuccess:@"取消成功"];
            [self addCollectionTongji:@"1"];
            for (ASHomeMainModel *subM in self.collectionArr) {
                if ([subM.tID isEqualToString:self.model.tID] && [subM.thumb isEqualToString:self.model.thumb]) {
                    [self.collectionArr removeObject:subM];
                    break;
                }
            }
        }else{
            self.model.is_collect = @"1";
            [self.imageArr replaceObjectAtIndex:0 withObject:@"details_ysc"];
            [self.titleArr replaceObjectAtIndex:0 withObject:@"已收藏"];
            [MBProgressHUD showSuccess:@"收藏成功"];
            [self addCollectionTongji:@"0"];
            [self.collectionArr addObject:self.model];
        }
        [self.collectionView reloadData];
    }
}

///保存收藏数据
- (void)saveCollectionData{
    NSString * temp  = NSTemporaryDirectory();
    NSString * filePath;
    if (self.type == 1) {
        filePath = [temp stringByAppendingPathComponent:ExpressionCollection];
    }else{
        filePath = [temp stringByAppendingPathComponent:COLLECTIONKEY];
    }
    [NSKeyedArchiver archiveRootObject:self.collectionArr toFile:filePath];
    [[NSNotificationCenter defaultCenter]postNotificationName:COLLECTIONCHANGE object:nil];
}

///下载图片
- (void)downLoadData{
    if (self.model.canSave) {
        [MBProgressHUD showError:@"已下载"];
        return;
    }
    [ASTool addUMTongJiKey:@"details" subKey:self.type>0?@"expression_detail":@"portrail_detail" titleStr:@"保存"];
    [[SDWebImageManager sharedManager]loadImageWithURL:[NSURL URLWithString:self.model.thumb] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (image) {
            [self saveImage:image];
            [self addDownLoadTongji];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"保存失败"];
            });
        }
    }];
}

- (void)saveImage:(UIImage *)image{
    FELog(@"asdfsadfsadfasd====%@",image);
    ///开启相册权限
    NSString * title = [ASTool appName];
    if (self.type == 1) {
        title = [NSString stringWithFormat:@"%@(表情)",title];
    }
    [[BDFCustomPhotoAlbum shareInstance]saveToNewThumb:image ifPush:NO subTitle:title showHUD:YES completion:^(BOOL isSucceed, PHAuthorizationStatus photoType) {
        if (!isSucceed) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showPhotoAlertView:photoType];
            });
        }else{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"SavePhotoSucceed" object:nil];
            self.model.canSave = YES;
        }
    }];
}

///弹出设置提示
- (void)showPhotoAlertView:(PHAuthorizationStatus)status{
    if (@available(iOS 14.0, *)) {
        if (status == PHAuthorizationStatusLimited) {
            return;
        }
    }
    NSString *contentStr = @"请在设置中为我们打开权限，以保存图片";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:contentStr preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alerOne = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
    UIAlertAction *alerTwo = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
    }];
    [alert addAction:alerOne];
    [alert addAction:alerTwo];
    [currViewController() presentViewController:alert animated:YES completion:nil];
}

///下载统计
- (void)addDownLoadTongji{
    [ASHomeApi addDownLoadTongji:self.model.tID completion:^(id  _Nonnull result) {
    } failure:^(NSError * _Nonnull error) {
    }];
}

///收藏统计
- (void)addCollectionTongji:(NSString *)collectionType{
    [ASHomeApi addCollectionTongji:self.model.tID is_cancel:collectionType completion:^(id  _Nonnull result) {
    } failure:^(NSError * _Nonnull error) {
    }];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
